# coding=utf-8
import json

__author__ = 'daihaibin'

class ViewErrorCode(object):
    def __init__(self, error_code, description=None):
        if not isinstance(error_code, int):
            raise TypeError('Int type error code required.')
        self.error_code = error_code
        self.description = description

    def to_json(self):
        return json.dumps(self.__dict__)

def transform_model_by_id_decorator(model_id_key_name, model, dose_not_exist_redirect = None):
    """
    根据模型Id获取模型
    """
    def decorator(view_func):
        def _wrapped_view_func(request, *args, **kwargs):
            if model_id_key_name in kwargs:
                model_id = kwargs[model_id_key_name]
                try:
                    model_instance = getattr(model, 'objects').get(id = model_id)
                    kwargs[model_id_key_name] = model_instance
                except Exception as e:
                    if dose_not_exist_redirect:
                        return dose_not_exist_redirect
            return view_func(request, *args, **kwargs)
        return _wrapped_view_func
    return decorator

def format_response_decorator(target_format = 'html', format_redirect = None):
    def decorator(view_func):
        def _wrapped_view_func(request, *args, **kwargs):
            if 'format' in request.REQUEST:
                format = request.REQUEST.get('format')
                if format:
                    format = format.lower()
                    if format == target_format:
                        if format_redirect:
                            return format_redirect
            return view_func(request, *args, **kwargs)
        return _wrapped_view_func
    return decorator